package com.kangaroo.register;

import com.kangaroo.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;

/**
 * @Description:使用zk发现服务
 * @author ;liub
 * @Date: 2018-02-02 10:37
**/
@Slf4j
public class ZKServiceDiscover {

    private final String ZK_REGISTRY_PATH="lb";

    public String discover(String name){
        ZkClient zkClient=new ZkClient("127.0.0.1:2181",5000,1000);
        log.debug("zk 服务发现");
        try{
            // 获取 service 节点
            String servicePath = ZK_REGISTRY_PATH + "/" + name;
            if (!zkClient.exists(servicePath)) {
                throw new RuntimeException(String.format("can not find any service node on path: %s", servicePath));
            }
            List<String> addressList = zkClient.getChildren(servicePath);
            if (CollectionUtil.isEmpty(addressList)) {
                throw new RuntimeException(String.format("can not find any address node on path: %s", servicePath));
            }
           String address=addressList.get(0);
            String addressPath = servicePath + "/" + address;
            System.out.println("zkClient.readData(addressPath)="+zkClient.readData(addressPath));
            return zkClient.readData(addressPath);

        }finally {
            zkClient.close();
        }
    }

}